import 'package:get/get.dart';
import 'package:kkhousekeep/page/home/home_page_controller.dart';
import 'package:kkhousekeep/page/login/login_controller.dart';
import 'package:kkhousekeep/page/me/me_controller.dart';
import 'package:kkhousekeep/tools/shared_preferences.dart';
import 'package:kkhousekeep/tools/toast_util.dart';

import '../../net/home_connect.dart';
import '../../net/me_account_connect.dart';

class HomeMainController extends GetxController {
  var currentId = 0.obs;
  late HomeConnect _connect;
  final UserType userType;



  HomeMainController(this.userType, {
    required int index,
  }) {
    currentId.value = index;
  }

  bool roomCheckPass = false;

  @override
  void onInit() {
    super.onInit();
    _initRoomCheckPass();
  }

  Future<void> _initRoomCheckPass() async {
    if (userType == UserType.property) {
      roomCheckPass = true;
      return;
    }
    roomCheckPass = await getSp().getRoomCheckPass();
    if (!roomCheckPass) {
      _connect = Get.find<HomeConnect>();
    }
  }

  void switchBarItem(int index) async {
    if (!roomCheckPass && index == 0) {
      var response = await _connect.checkHomeBind();
      if (response == null) {
        return;
      }
      if (response.obj.roomCheckPass == false) {
        ToastUtils.showToast(tip: "绑定房屋后可开启更多功能");
        return;
      }
      roomCheckPass = true;
      await getSp().setAccessToken(response.obj.token);
      await getSp().setRoomCheckPass(true);
      await getSp().setUserType(_getUserType(response.obj.ownerType));
      var meAccountConnect = Get.isRegistered<MeAccountConnect>()
          ? Get.find<MeAccountConnect>()
          : Get.put(MeAccountConnect());
      var userInfo = await meAccountConnect.getUserInfo();
      await getSp().setUid(userInfo?.id ?? -1);
      await getSp().setUserHeadPortrait(userInfo?.image ?? "");
    }
    currentId.value == 0
        ? Get.isRegistered<MeController>()
            ? Get.find<MeController>().loadSpData()
            : Get.put(MeController()).loadSpData()
        : Get.isRegistered<HomeController>()
            ? Get.find<HomeController>().loadNetworkData()
            : Get.put(HomeController()).loadNetworkData();
    currentId.value = index;
  }

  UserType _getUserType(String userValue) {
    return UserType.values.firstWhere((element) => element.value == userValue);
  }
}
